/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @see https://leetcode-cn.com/problems/merge-sorted-array/solution/he-bing-liang-ge-you-xu-shu-zu-by-leetcode/
 * @description 从前往后遍历，需要空间存放。从后往前遍历，直接修改nums1数组即可，因为有0占位
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {
  // m > n
  let i = 0;
  let j = 0;
  let finalArray = [];
  while(true) {
    console.log(i, j, finalArray)
    // num1 数组循环到最后了，拼接剩余的num2数组
    if(i >= m) {
      // finalArray.push(getElement(nums1, i));
      finalArray = finalArray.concat(getLeftItems(nums2, j, n));
      break;
    }
    // num2循环到底了，把剩余的num1数组拼接到结果数组内
    if(j >= n) {
      // finalArray.push(getElement(nums1, i));
      finalArray = finalArray.concat(getLeftItems(nums1, i, m));
      break;
    }
    const ele1 = getElement(nums1, i);
    const ele2 = getElement(nums2, j);
    if(ele1 < ele2) {
      // 这里可以用splice方法插入两个数据
      finalArray.push(ele1);
      i++;
      continue;
    } else {
      finalArray.push(ele2);
      j++;
      continue;
    }
  }
  nums1 = finalArray;
  for (let index = 0; index < finalArray.length; index++) {
    nums1[index] = finalArray[index];
  }
  console.log(nums1)
};

merge([1,2,3, 0, 0, 0], 3, [2, 5, 6], 3);

function getLeftItems(arr, startIndex, nums) {
  let leftArr = [];
  for (; startIndex < nums; startIndex++) {
    leftArr.push(arr[startIndex]);
  }
  return leftArr;
}

function getElement(arr, index) {
  return arr[index];
}